package com.tarena.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang.StringUtils;

import com.tarena.dao.UserDao;
import com.tarena.domain.User;

public class AddUserServlet implements Servlet {

	public void destroy() {

	}

	public ServletConfig getServletConfig() {
		return null;
	}

	public String getServletInfo() {
		return null;
	}

	public void init(ServletConfig arg0) throws ServletException {
	}

	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		try{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String[] favorite = request.getParameterValues("favorite");
		
		String fa = StringUtils.join(favorite,";");
		User user = new User();
			user.setName(name);
			user.setPassword(password);
			user.setEmail(email);
			user.setFavorite(fa);
	
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<html>");
		out.println("<head>" +
								"<title>Infomation...</title>" +
						"</head>");
		out.println("<body>");
		UserDao ud = new UserDao();
		boolean flag = ud.validate(user);
		if( flag ) {
			out.println("<h1>注册成功</h1>");
			ud.insertUser(user);
		} else {
			out.println("<h1>注册失败</h1>");
			out.println("<a href='register'>返回</a>");
		}
		out.println("</body>");
		out.println("</html>");
		} catch (Exception e) {
			throw new ServletException(e);
		} 
		
	}
}